package com.neu.yth.nepBackend.member.utils;

import com.neu.yth.nepBackend.member.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


/**
 * @ClassName SmsComponent
 * @Description
 * @Author YTH
 * @Date 2024-06-02 20:59
 */
@Component
@Slf4j
public class SmsComponent {

    @Value("${sms.send-url}")
    private String sendCodeUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    @Async("threadPoolTaskExecutor")
    public void send(String mobile, String code, int minute) {
        MultiValueMap<String, String> querys = new LinkedMultiValueMap<>();
        querys.add("mobile", mobile);
        querys.add("param", String.format("**code**:%s,**minute**:%d", code, minute));
        querys.add("smsSignId", smsConfig.getSmsSignId());
        querys.add("templateId", smsConfig.getTemplateId());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());

        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(querys, headers);

        System.out.println(entity.toString());

        ResponseEntity<String> response = restTemplate.postForEntity(sendCodeUrl, entity, String.class);
        log.info("发送短信，mobile: {}, code: {}, 响应: {}", mobile, code, response.getBody());
        if (!response.getStatusCode().is2xxSuccessful()) {
            log.error("短信发送失败，mobile: {}, code: {}, 响应: {}", mobile, code, response.getBody());
        } else {
            log.info("短信发送成功，mobile: {}, code: {}, 响应: {}", mobile, code, response.getBody());
        }
//        String url = String.format(sendCodeUrl, to, templateId, value);
//        System.out.println(url);
//        HttpHeaders headers = new HttpHeaders();
//        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
//
//        HttpEntity<String> entity = new HttpEntity<>(headers);
//
//
//        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
//        log.info("url:{},body:{}", url, response.getBody());
//        if (!response.getStatusCode().is2xxSuccessful()) {
//            log.error("短信发送失败，value:{}，响应:{}", value,response.getBody());
//        }else{
//            log.info("短信发送成功，value:{}，响应:{}",value, response.getBody());
//        }
    }
}
